%%%-------------------------------------------------------------------
%%% @author glendy
%%% @copyright (C) 2025, <COMPANY>
%%% @doc
%%%
%%% @end
%%% Created : 16. 10月 2025 8:44
%%%-------------------------------------------------------------------
-module(redis_encode).
-author("glendy").

-include("redis_driver.hrl").

%% API
-export([
  encode/1
]).

encode(StrList) when is_list(StrList) ->
  StrListLen = length(StrList),
  StrListLenBin = list_to_binary(integer_to_list(StrListLen)),
  HeaderBin = <<$*, StrListLenBin/binary, ?NL>>,
  lists:foldl(
    fun(Item, BinAcc0) ->
      ItemBin = encode(Item),
      <<BinAcc0/binary, ItemBin/binary>>
    end, HeaderBin, StrList);
encode(StrBin) when is_binary(StrBin) ->
  StrBinLen = size(StrBin),
  StrBinLenBin = list_to_binary(integer_to_list(StrBinLen)),
  <<$$, StrBinLenBin/binary, ?NL, StrBin/binary, ?NL>>;
encode(Int) when is_integer(Int) ->
  IntBin = list_to_binary(integer_to_list(Int)),
  <<$:, IntBin/binary, ?NL>>;
encode(Float) when is_float(Float) ->
  FloatBin = list_to_binary(float_to_list(Float)),
  encode(FloatBin);
encode(Atom) when is_atom(Atom) ->
  AtomBin = atom_to_binary(Atom, latin1),
  encode(AtomBin).
